//
//  VideoDownLoadOperation.m
//  News
//
//  Created by lanou3g on 15/11/10.
//  Copyright © 2015年 songhaowen. All rights reserved.
//

#import "VideoDownLoadOperation.h"
#import "VideoModel.h"

@interface VideoDownLoadOperation () <NSURLSessionDelegate>

/** 用于保存传过来的model */
@property (nonatomic, strong) VideoModel *downloadVideoModel;
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
/** 计算速度 */
@property (nonatomic, assign) CGFloat speedBytes;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSMutableURLRequest *request;
@property (nonatomic, strong) NSURLSession *session;
/** 断点下载点 */
@property (nonatomic, assign) long long reloadBytes;

@property (nonatomic, strong) NSData *data;


@end

@implementation VideoDownLoadOperation

// 持有模型
- (instancetype)initWithDownloadVideoModel:(VideoModel *)model
{
    if (self = [super init]) {
        self.downloadVideoModel = model;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(caculateSpeed) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    return self;
}

// 开始下载(任务加到队列中会自动执行该方法)
- (void)main
{
    // 1. 初始化session
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    
    // 2. 初始化request
    self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.downloadVideoModel.mp4_url]];
    
    // 3. 用session加载request
    self.task = [self.session downloadTaskWithRequest:self.request];
    
    // 4. 开始任务
    [self.task resume];
}

// 暂停下载
- (void)downloadPause
{
//    [self.task suspend];
    [_task cancelByProducingResumeData:^(NSData *resumeData) {
        _data = resumeData;
    }];
    _task = nil;
}

// 恢复下载
- (void)downloadResume
{
    
    if(!_data){
        NSURL *url = [NSURL URLWithString:self.downloadVideoModel.mp4_url];
        _request = [NSMutableURLRequest requestWithURL:url];
        _task = [_session downloadTaskWithRequest:_request];
    }else{
        _task = [_session downloadTaskWithResumeData:_data];
    }
    [_task resume];
    
    // 断点下载
//    NSString *range = [NSString stringWithFormat:@"bytes=%lld-", self.reloadBytes];
//    [self.request addValue:range forHTTPHeaderField:@"Range"];
//    self.task = [self.session downloadTaskWithRequest:self.request];
//    
//    // 恢复下载
//    [self.task resume];
}

// 计算速度
- (void)caculateSpeed
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.speedBlock) {
            self.speedBlock(self.speedBytes, self.downloadVideoModel);
        }
        self.speedBytes = 0;
    });
    
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"下载完成");
    
    // 取消时钟
    [self.timer invalidate];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager moveItemAtPath:location.path toPath:path error:nil];
    
    // 将路径存起来, 以便以后播放
    self.downloadVideoModel.videoPath = path;
    
    // 下载完成发送通知
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:k_videoDidDownedFinishedSuccess object:self.downloadVideoModel];
        self.downloadVideoModel.isDownFinished = YES;
    });
    
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    // 计算文件大小
    // 防止断点重新计算未下载部分的大小
    if (!self.downloadVideoModel.videoSize) {
        self.downloadVideoModel.videoSize = totalBytesExpectedToWrite;
    }
    
    // 计算下载速度
    self.speedBytes += bytesWritten;
    // 计算断点下载点
    self.reloadBytes += bytesWritten;
    
    // 计算进度
    self.downloadVideoModel.videoProgress = self.reloadBytes / self.downloadVideoModel.videoSize;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.updateBlock) {
            self.updateBlock(self.downloadVideoModel);
        }
    });
}

- (NSData *)data
{
    if (_data == nil) {
        _data = [NSData data];
    }
    return _data;
}

@end
